package com.whpost.service.tools;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.text.StringEscapeUtils;
import java.util.HashMap;
import java.util.Map;

public class XSSFilterJSON {

    public static String xssFilterJson(String jsonStr) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Object jsonData = objectMapper.readValue(jsonStr, Object.class);
            Object filteredData = filter(jsonData);
            return objectMapper.writeValueAsString(filteredData);
        } catch (Exception e) {
            return jsonStr;
        }
    }

    private static Object filter(Object value) {
        if (value instanceof String) {
            return StringEscapeUtils.escapeHtml4((String) value);
        } else if (value instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) value;
            Map<String, Object> filteredMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                filteredMap.put(entry.getKey(), filter(entry.getValue()));
            }
            return filteredMap;
        } else if (value instanceof Object[]) {
            Object[] array = (Object[]) value;
            for (int i = 0; i < array.length; i++) {
                array[i] = filter(array[i]);
            }
            return array;
        }
        return value;
    }

    public static void main(String[] args) {
        String jsonStr = "{\"name\": \"<script>alert('XSS')</script>\", \"hobbies\": [\"<b>reading</b>\", \"swimming\"]}";
        String filteredJson = xssFilterJson(jsonStr);
        System.out.println(filteredJson);
    }
}